<template>
  <div class="app-container">
    <!-- 电价配置管理区域 -->
    <el-card class="config-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">电价配置管理</span>
          <div class="header-actions">
            <el-button
              type="primary"
              icon="Plus"
              @click="handleAddSetting"
              v-hasPermi="['device:electricitySetting:add']"
              >新增配置</el-button
            >
            <el-button
              type="success"
              icon="Download"
              @click="handleExportSettings"
              v-hasPermi="['device:electricitySetting:export']"
              >导出配置</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        v-loading="settingsLoading"
        :data="settingsList"
        style="width: 100%"
        @row-click="handleSettingRowClick"
        :row-class-name="getSettingRowClassName"
      >
        <el-table-column prop="name" label="配置名称" width="200" />
        <el-table-column prop="provinceCode" label="省份" width="100" />
        <el-table-column prop="cityCode" label="城市" width="100" />
        <el-table-column prop="districtCode" label="区县" width="100" />
        <el-table-column prop="isBase" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.isBase === 1 ? 'success' : 'info'">
              {{ scope.row.isBase === 1 ? "生效中" : "未生效" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="默认电价" width="150">
          <template #default="scope">
            {{
              scope.row.price ? "¥" + Number(scope.row.price).toFixed(2) : "-"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="起效时间" width="180">
          <template #default="scope">
            {{ scope.row.startTime || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          width="200"
          label="备注"
          show-overflow-tooltip
        />
        <el-table-column prop="createAt" label="创建时间" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.createAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button
              type="text"
              icon="View"
              @click.stop="handleOpenTimeConfigDialog(scope.row)"
              v-hasPermi="['device:electricitySetting:view']"
              >详情</el-button
            >
            <el-button
              type="text"
              icon="Edit"
              @click.stop="handleEditSetting(scope.row)"
              v-hasPermi="['device:electricitySetting:edit']"
              >编辑</el-button
            >
            <el-button
              v-if="scope.row.isBase !== 1"
              type="text"
              icon="Check"
              @click.stop="handleSetActive(scope.row)"
              v-hasPermi="['device:electricitySetting:activate']"
              >设为生效</el-button
            >
            <el-button
              type="text"
              icon="Delete"
              @click.stop="handleDeleteSetting(scope.row)"
              v-hasPermi="['device:electricitySetting:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <el-pagination
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 时段配置区域已移除，改由配置表“详情”按钮进入弹窗 -->

    <!-- 时段配置对话框 -->
    <el-dialog
      title="时段配置管理"
      v-model="timeConfigDialogVisible"
      width="90%"
      append-to-body
      destroy-on-close
    >
      <div class="time-config-dialog">
        <!-- 24小时时间轴可视化 -->
        <div class="time-axis-container">
          <div class="time-axis-header">
            <div class="time-labels">
              <div v-for="hour in 24" :key="hour" class="time-label">
                {{ String(hour - 1).padStart(2, "0") }}:00
              </div>
            </div>
          </div>
          <div class="time-axis-content">
            <div class="time-slots">
              <div
                v-for="(item, index) in timeItems"
                :key="index"
                class="time-slot"
                :style="getTimeSlotStyle(item)"
                @click="handleEditTimeItem(item, index)"
              >
                <span class="time-range"
                  >{{ item.startTime }} - {{ item.endTime }}</span
                >
                <span class="electricity-type">{{ item.electricityType }}</span>
                <span class="price"
                  >¥{{ (Number(item.price) || 0).toFixed(2) }}</span
                >
              </div>
            </div>
          </div>
        </div>

        <!-- 时段配置表格 -->
        <el-table
          v-loading="timeItemsLoading"
          :data="timeItems"
          style="width: 100%; margin-top: 20px"
          @sort-change="handleSortChange"
        >
          <el-table-column
            prop="sortOrder"
            label="排序"
            width="120"
            sortable="custom"
          />
          <el-table-column prop="startTime" label="开始时间" width="220">
            <template #default="scope">
              <el-time-picker
                v-model="scope.row.startTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="开始时间"
                style="width: 180px"
                @change="handleTimeChange(scope.$index, 'startTime')"
              />
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="220">
            <template #default="scope">
              <el-time-picker
                v-model="scope.row.endTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="结束时间"
                style="width: 180px"
                @change="handleTimeChange(scope.$index, 'endTime')"
              />
            </template>
          </el-table-column>
          <el-table-column prop="electricityType" label="电价类型" width="180">
            <template #default="scope">
              <el-select
                v-model="scope.row.electricityType"
                placeholder="选择类型"
                style="width: 140px"
              >
                <el-option
                  v-for="item in electricityTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="电价(元/kWh)" width="180">
            <template #default="scope">
              <el-input
                v-model="scope.row.price"
                placeholder="电价"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            width="200"
            show-overflow-tooltip
          >
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button
                type="text"
                icon="Delete"
                @click="handleDeleteTimeItem(scope.$index)"
                v-hasPermi="['device:electricitySetting:timeRemove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 时间覆盖验证提示 -->
        <div
          v-if="timeValidationMessage"
          class="validation-message"
          :class="timeValidationMessage.type"
        >
          <el-icon><Warning /></el-icon>
          <span>{{ timeValidationMessage.text }}</span>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            icon="Plus"
            @click="handleAddTimeItem"
            v-hasPermi="['device:electricitySetting:timeAdd']"
            >新增时段</el-button
          >
          <el-button
            type="warning"
            icon="Refresh"
            @click="handleResetTimeConfig"
            v-hasPermi="['device:electricitySetting:timeReset']"
            >重置配置</el-button
          >
          <el-button
            type="success"
            icon="Check"
            @click="handleSaveTimeConfig"
            v-hasPermi="['device:electricitySetting:timeSave']"
            >保存配置</el-button
          >
          <el-button @click="timeConfigDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 电价配置对话框 -->
    <el-dialog
      :title="settingDialogTitle"
      v-model="settingDialogVisible"
      width="50%"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="settingFormRef"
        :model="settingForm"
        :rules="settingRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="name">
              <el-input
                v-model="settingForm.name"
                placeholder="请输入配置名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否生效" prop="isBase">
              <el-switch
                v-model="settingForm.isBase"
                :active-value="1"
                :inactive-value="0"
                active-text="生效"
                inactive-text="未生效"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="默认电价" prop="price">
              <el-input-number
                v-model="settingForm.price"
                :min="0"
                :precision="2"
                placeholder="请输入默认电价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起效时间" prop="startTime">
              <el-date-picker
                v-model="settingForm.startTime"
                type="datetime"
                placeholder="请选择起效时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="省份" prop="provinceCode">
              <el-input
                v-model="settingForm.provinceCode"
                placeholder="请输入省份"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="城市" prop="cityCode">
              <el-input
                v-model="settingForm.cityCode"
                placeholder="请输入城市"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区县" prop="districtCode">
              <el-input
                v-model="settingForm.districtCode"
                placeholder="请输入区县"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="settingForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="handleSubmitSetting"
            v-hasPermi="['device:electricitySetting:save']"
            >确 定</el-button
          >
          <el-button @click="settingDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Warning } from "@element-plus/icons-vue";
import {
  getElectricitySettingList,
  getElectricitySettingDetail,
  saveElectricitySetting,
  delElectricitySetting,
  setActiveElectricitySetting,
  exportElectricitySetting,
} from "@/api/deviceManage/electricitySetting";
import {
  batchAddElectricitySetting,
  getElectricityItemList,
  getElectricityItemsBySettingId,
  getElectricityItemDetail,
  saveElectricityItem,
  delElectricityItem,
  batchSaveElectricityItems,
  getElectricityAllItems,
} from "@/api/deviceManage/electricityItem";
import {
  ELECTRICITY_TYPE_OPTIONS,
  getElectricityTypeTagType,
  getElectricityTypeColor,
} from "@/utils/enums";

// 响应式数据
const settingsList = ref([]);
const settingsLoading = ref(false);
const currentSetting = ref(null);
const timeItems = ref([]);
const timeItemsLoading = ref(false);
const total = ref(0);

// 分页查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 对话框相关
const settingDialogVisible = ref(false);
const settingDialogTitle = ref("");
const settingFormRef = ref();
const timeConfigDialogVisible = ref(false);

// 表单数据
const settingForm = reactive({
  id: null,
  name: "",
  provinceCode: "",
  cityCode: "",
  districtCode: "",
  isBase: 0,
  price: null, // 默认电价（元/kWh）
  startTime: "", // 起效时间
  remark: "",
});

// 表单验证规则
const settingRules = reactive({
  name: [{ required: true, message: "配置名称不能为空", trigger: "blur" }],
});

// 电价类型选项
const electricityTypeOptions = ELECTRICITY_TYPE_OPTIONS;

// 时间验证消息
const timeValidationMessage = ref(null);

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return "-";
  const date = new Date(dateStr);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
}

// 获取配置行样式
function getSettingRowClassName({ row }) {
  return row.isBase === 1 ? "active-setting-row" : "";
}

// 获取时段样式
function getTimeSlotStyle(item) {
  const color = getElectricityTypeColor(item.electricityType);
  const startPercent = getTimePercent(item.startTime);
  const endPercent = getTimePercent(item.endTime);
  const width = endPercent - startPercent;

  return {
    left: `${startPercent}%`,
    width: `${width}%`,
    backgroundColor: color,
    borderColor: color,
  };
}

// 将时间转换为百分比
function getTimePercent(timeStr) {
  if (!timeStr) return 0;
  const [hours, minutes] = timeStr.split(":").map(Number);
  return ((hours * 60 + minutes) / (24 * 60)) * 100;
}

// 查询配置列表
async function getSettingsList() {
  settingsLoading.value = true;
  try {
    const response = await getElectricitySettingList({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
    });
    settingsList.value = response.data?.list || response.rows || [];
    total.value = response.data?.total ?? response.total ?? 0;
  } catch (error) {
    console.error("获取配置列表失败:", error);
    ElMessage.error("获取配置列表失败");
  } finally {
    settingsLoading.value = false;
  }
}

// 分页事件
function handleSizeChange(size) {
  queryParams.pageSize = size;
  queryParams.pageNum = 1;
  getSettingsList();
}

function handleCurrentChange(page) {
  queryParams.pageNum = page;
  getSettingsList();
}

// 查询时段配置详情
async function getTimeItems(settingId) {
  if (!settingId) return;

  timeItemsLoading.value = true;
  try {
    const response = await getElectricitySettingDetail(settingId);
    const items = response.data.itemList || [];

    // 处理时间格式，添加时间选择器需要的格式
    const mapped = items.map((item) => ({
      ...item,
      startTime: item.startTime,
      endTime: item.endTime,
    }));

    // 若无时段，默认按每小时生成24条，覆盖全天
    if (mapped.length === 0 && currentSetting.value) {
      timeItems.value = generateDefault24HourItems(currentSetting.value.id);
    } else {
      timeItems.value = mapped;
    }

    validateTimeCoverage();
  } catch (error) {
    console.error("获取时段配置失败:", error);
    ElMessage.error("获取时段配置失败");
  } finally {
    timeItemsLoading.value = false;
  }
}

// 生成默认24小时（每小时一条）时段
function generateDefault24HourItems(settingId) {
  const items = [];
  // 30分钟一段，共48段，最后一段结束为 23:59:59
  const segmentMinutes = 30;
  let order = 1;
  for (let minutes = 0; minutes < 24 * 60; minutes += segmentMinutes) {
    const begin = minutesToHHMM(minutes);
    const next = minutes + segmentMinutes;
    const isLast = next >= 24 * 60;
    const end = isLast ? "23:59:59" : minutesToHHMM(next);
    items.push({
      id: null,
      settingId,
      startTime: begin,
      endTime: end,
      electricityType: "平段",
      price: 0,
      sortOrder: order++,
      remark: "",
    });
  }
  return items;
}

function minutesToHHMM(total) {
  const h = Math.floor(total / 60);
  const m = total % 60;
  return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
}

// 验证时间覆盖
function validateTimeCoverage() {
  if (timeItems.value.length === 0) {
    timeValidationMessage.value = {
      type: "warning",
      text: "请添加时段配置",
    };
    return;
  }

  // 按开始时间排序
  const sortedItems = [...timeItems.value].sort((a, b) => {
    return timeToMinutes(a.startTime) - timeToMinutes(b.startTime);
  });

  // 检查是否有重叠
  for (let i = 0; i < sortedItems.length - 1; i++) {
    const current = sortedItems[i];
    const next = sortedItems[i + 1];

    if (timeToMinutes(current.endTime) > timeToMinutes(next.startTime)) {
      timeValidationMessage.value = {
        type: "error",
        text: "时间段存在重叠，请检查配置",
      };
      return;
    }
  }

  // 检查是否覆盖24小时
  const totalMinutes = sortedItems.reduce((total, item) => {
    return (
      total + (timeToMinutes(item.endTime) - timeToMinutes(item.startTime))
    );
  }, 0);

  if (totalMinutes !== 24 * 60) {
    timeValidationMessage.value = {
      type: "warning",
      text: `时间段未完全覆盖24小时，当前覆盖${
        Math.round((totalMinutes / 60) * 100) / 100
      }小时`,
    };
  } else {
    timeValidationMessage.value = null;
  }
}

// 时间转分钟
function timeToMinutes(timeStr) {
  if (!timeStr) return 0;
  const parts = timeStr.split(":").map(Number);
  const hours = parts[0] || 0;
  const minutes = parts[1] || 0;
  const seconds = parts[2] || 0;
  // 若有秒，按向上取整到分钟，确保 23:59:59 计入整天覆盖
  const add = seconds > 0 ? 1 : 0;
  return Math.min(24 * 60, hours * 60 + minutes + add);
}

// 配置行点击
function handleSettingRowClick(row) {
  currentSetting.value = row;
  getTimeItems(row.id);
}

// 新增配置
function handleAddSetting() {
  settingDialogTitle.value = "新增电价配置";
  Object.assign(settingForm, {
    id: null,
    name: "",
    provinceCode: "",
    cityCode: "",
    districtCode: "",
    isBase: 0,
    price: null, // 默认电价（元/kWh）
    startTime: "", // 起效时间
    remark: "",
  });
  settingDialogVisible.value = true;
}

// 编辑配置
function handleEditSetting(row) {
  settingDialogTitle.value = "编辑电价配置";
  Object.assign(settingForm, row);
  settingDialogVisible.value = true;
}

// 删除配置
function handleDeleteSetting(row) {
  ElMessageBox.confirm(`是否确认删除配置"${row.name}"？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delElectricitySetting([row.id]).then(() => {
      ElMessage.success("删除成功");
      getSettingsList();
      if (currentSetting.value?.id === row.id) {
        currentSetting.value = null;
        timeItems.value = [];
      }
    });
  });
}

// 设为生效
function handleSetActive(row) {
  ElMessageBox.confirm(
    `是否将配置"${row.name}"设为生效？设为生效后，其他配置将自动取消生效状态。`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    setActiveElectricitySetting(row.id).then(() => {
      ElMessage.success("设置成功");
      getSettingsList();
    });
  });
}

// 提交配置
function handleSubmitSetting() {
  settingFormRef.value.validate((valid) => {
    if (valid) {
      saveElectricitySetting(settingForm).then(() => {
        ElMessage.success(settingForm.id ? "修改成功" : "新增成功");
        settingDialogVisible.value = false;
        getSettingsList();
      });
    }
  });
}

// 打开时段配置对话框（可从列表行进入或使用当前选择的配置）
async function handleOpenTimeConfigDialog(row) {
  const target = row || currentSetting.value;
  if (!target) {
    ElMessage.warning("请先选择或创建电价配置");
    return;
  }
  currentSetting.value = target;
  // 预先加载该配置的时段数据，再打开弹窗
  await getTimeItems(target.id);
  timeConfigDialogVisible.value = true;
}

// 新增时段
function handleAddTimeItem() {
  if (!currentSetting.value) {
    ElMessage.warning("请先选择或创建电价配置");
    return;
  }

  // 如果当前为空，则一键生成24小时（半小时段）；否则追加半小时
  if (timeItems.value.length === 0) {
    timeItems.value = generateDefault24HourItems(currentSetting.value.id);
  } else {
    const last = timeItems.value[timeItems.value.length - 1];
    const lastEnd = last?.endTime || "00:00";
    if (lastEnd === "23:59:59") {
      ElMessage.info("已覆盖全天，无法继续追加");
      return;
    }
    const minutes = timeToMinutes(lastEnd);
    const begin = minutesToHHMM(minutes % (24 * 60));
    const next = minutes + 30;
    const end = next >= 24 * 60 ? "23:59:59" : minutesToHHMM(next);
    timeItems.value.push({
      id: null,
      settingId: currentSetting.value.id,
      startTime: begin,
      endTime: end,
      electricityType: "平段",
      price: 0,
      sortOrder: timeItems.value.length + 1,
      remark: "",
    });
  }
}

// 编辑时段
function handleEditTimeItem(item, index) {
  // 可以在这里添加编辑逻辑
}

// 删除时段
function handleDeleteTimeItem(index) {
  timeItems.value.splice(index, 1);
  validateTimeCoverage();
}

// 时间变化处理
function handleTimeChange(index, type) {
  const item = timeItems.value[index];
  // 时间选择器已经自动更新了 v-model 绑定的值
  // 这里只需要触发验证即可
  validateTimeCoverage();
}

// 排序变化
function handleSortChange({ column, prop, order }) {
  if (prop === "sortOrder") {
    timeItems.value.sort((a, b) => {
      return order === "ascending"
        ? a.sortOrder - b.sortOrder
        : b.sortOrder - a.sortOrder;
    });
  }
}

// 重置时段配置
function handleResetTimeConfig() {
  timeItems.value = [];
  timeValidationMessage.value = null;
}

// 保存时段配置（批量）
function handleSaveTimeConfig() {
  if (!currentSetting.value) {
    ElMessage.warning("请先选择电价配置");
    return;
  }

  if (timeValidationMessage.value?.type === "error") {
    ElMessage.warning("请先解决时间段重叠问题");
    return;
  }

  const items = timeItems.value.map((item, index) => ({
    id: item.id ?? null,
    settingId: currentSetting.value.id,
    startTime: item.startTime || item.startTime,
    endTime: item.endTime || item.endTime,
    electricityType: item.electricityType,
    price: item.price ?? 0,
    sortOrder: index + 1,
    remark: item.remark || "",
  }));

  // 批量提交对象数组
  batchAddElectricitySetting(items).then(() => {
    ElMessage.success("保存成功");
    getTimeItems(currentSetting.value.id);
    timeConfigDialogVisible.value = false;
  });
}

// 导出配置
function handleExportSettings() {
  // 实现导出逻辑
  ElMessage.info("导出功能开发中...");
}

// 页面初始化
onMounted(() => {
  getSettingsList();
});
</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";

.app-container {
  padding: 20px;
  background: $base-menu-background;
  min-height: 100vh;
}

.table-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0 0 0;
}

// 卡片样式
.config-card,
.time-config-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;

  :deep(.el-card__header) {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px 12px 0 0;
    border-bottom: 1px solid #e4e7ed;
    padding: 16px 20px;
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

// 卡片头部样式
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
  }

  .header-actions {
    display: flex;
    gap: 8px;

    .el-button {
      border-radius: 6px;
      font-weight: 500;

      &.el-button--primary {
        background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
        border: none;
        color: #ffffff;

        &:hover {
          background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
          color: #ffffff;
        }
      }

      &.el-button--success {
        background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
        border: none;
        color: #ffffff;

        &:hover {
          background: linear-gradient(135deg, #5daf34 0%, #529b2e 100%);
          color: #ffffff;
        }
      }

      &.el-button--warning {
        background: linear-gradient(135deg, #e6a23c 0%, #d19b3c 100%);
        border: none;
        color: #ffffff;

        &:hover {
          background: linear-gradient(135deg, #d19b3c 0%, #c8953a 100%);
          color: #ffffff;
        }
      }
    }
  }
}

// 表格样式
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;

  .el-table__header {
    th {
      background: #f8f9fa;
      color: #2c3e50;
      font-weight: 600;
      border-bottom: 2px solid #e4e7ed;
    }
  }

  .el-table__body {
    tr {
      &:hover {
        background: #f5f7fa;
      }

      &.active-setting-row {
        background: linear-gradient(
          135deg,
          rgba(79, 218, 202, 0.1) 0%,
          rgba(50, 183, 203, 0.1) 100%
        );
        border-left: 4px solid #4fdaca;
      }
    }
  }
}

// 操作按钮样式
:deep(.el-button--text) {
  color: #4fdaca !important;
  font-weight: 600 !important;
  border-radius: 6px !important;
  padding: 6px 12px !important;
  transition: all 0.3s ease !important;

  &:hover {
    color: #32b7cb !important;
    background: linear-gradient(
      135deg,
      rgba(79, 218, 202, 0.1) 0%,
      rgba(50, 183, 203, 0.1) 100%
    ) !important;
    transform: translateY(-1px) !important;
  }
}

// 预览样式已移除

// 时段配置对话框
.time-config-dialog {
  .time-axis-container {
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 20px;

    .time-axis-header {
      background: #f8f9fa;
      border-bottom: 1px solid #e4e7ed;
      padding: 8px 0;

      .time-labels {
        display: flex;
        position: relative;

        .time-label {
          flex: 1;
          text-align: center;
          font-size: 12px;
          color: #606266;
          font-weight: 500;
          position: relative;

          &::after {
            content: "";
            position: absolute;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 1px;
            height: 16px;
            background: #dcdfe6;
          }

          &:last-child::after {
            display: none;
          }
        }
      }
    }

    .time-axis-content {
      position: relative;
      min-height: 88px;
      background: #fafbfc;

      .time-slots {
        position: relative;
        height: 100%;

        .time-slot {
          position: absolute;
          top: 8px;
          min-height: 64px;
          border: 2px solid;
          border-radius: 6px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          transition: all 0.3s ease;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
            z-index: 10;
          }

          .time-range {
            font-size: 11px;
            font-weight: 600;
            color: #ffffff;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
            margin-bottom: 2px;
          }

          .electricity-type {
            font-size: 10px;
            font-weight: 500;
            color: #ffffff;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
            margin-bottom: 2px;
          }

          .price {
            font-size: 10px;
            font-weight: 600;
            color: #ffffff;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
          }
        }
      }
    }
  }
}

// 验证消息样式
.validation-message {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-radius: 6px;
  margin-top: 16px;
  font-size: 14px;
  font-weight: 500;

  &.warning {
    background: linear-gradient(135deg, #fff7e6 0%, #ffeaa7 100%);
    border: 1px solid #f39c12;
    color: #d68910;

    .el-icon {
      color: #f39c12;
      margin-right: 8px;
    }
  }

  &.error {
    background: linear-gradient(135deg, #fdf2f2 0%, #fecaca 100%);
    border: 1px solid #e53e3e;
    color: #c53030;

    .el-icon {
      color: #e53e3e;
      margin-right: 8px;
    }
  }

  &.success {
    background: linear-gradient(135deg, #f0fff4 0%, #c6f6d5 100%);
    border: 1px solid #38a169;
    color: #2f855a;

    .el-icon {
      color: #38a169;
      margin-right: 8px;
    }
  }
}

// 对话框样式
:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);

  .el-dialog__header {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px 12px 0 0;
    padding: 20px 24px;
    border-bottom: 1px solid #e4e7ed;

    .el-dialog__title {
      font-weight: 600;
      color: #2c3e50;
      font-size: 16px;
    }
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    padding: 16px 24px;
    background: #f8f9fa;
    border-radius: 0 0 12px 12px;
    border-top: 1px solid #e4e7ed;

    .el-button {
      border-radius: 6px;
      font-weight: 500;
      padding: 8px 20px;

      &.el-button--primary {
        background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
        border: none;
        color: #ffffff;

        &:hover {
          background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
          color: #ffffff;
        }
      }

      &:not(.el-button--primary) {
        background: #ffffff;
        border: 1px solid #dcdfe6;
        color: #606266;

        &:hover {
          background: #f5f7fa;
          border-color: #c0c4cc;
          color: #606266;
        }
      }
    }
  }
}

// 表单样式
:deep(.el-form) {
  .el-form-item__label {
    font-weight: 500;
    color: #2c3e50;
  }

  .el-input,
  .el-select,
  .el-input-number {
    .el-input__inner {
      border-radius: 6px;
      width: 100%;
      transition: all 0.3s ease;

      &:focus {
        border-color: #4fdaca;
        box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
      }
    }
  }

  .el-textarea {
    .el-textarea__inner {
      border-radius: 6px;
      border: 1px solid #dcdfe6;
      transition: all 0.3s ease;

      &:focus {
        border-color: #4fdaca;
        box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
      }
    }
  }

  .el-switch {
    .el-switch__core {
      border-radius: 20px;
      background: #dcdfe6;
      border: 1px solid #dcdfe6;

      &.is-checked {
        background: #4fdaca;
        border-color: #4fdaca;
      }
    }
  }
}

// 时间选择器样式
:deep(.el-time-picker) {
  width: 100%;

  .el-input__inner {
    border-radius: 6px;

    transition: all 0.3s ease;

    &:focus {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

// 数字输入框样式
:deep(.el-input-number) {
  width: 100%;

  .el-input__inner {
    border-radius: 6px;

    transition: all 0.3s ease;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;

    .header-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .time-axis-container {
    .time-labels {
      .time-label {
        font-size: 10px;
      }
    }
  }
}
</style>
